import moment from "moment";
import {
  getWorkingDayList,
  getOffDayList,
  addWorkingAndOffDay,
} from "../server/weekdaysApi";

const initData = {
  /* 工作日(每周）例：周一（班）周二（班）周三（班）周四（班）周五（班）周六（休）周日（休） */
  workingDayList: [],
  /* 从后端查询回来的补班/节假信息 */
  specialDay: {},
  /* 正在编辑的补班/节假信息 */
  specialDayTemp: {},
  /* 真正的补班/节假信息 = specialDay + specialDayTemp */
  realSpecialDay: [],
  /* 选中的日期 */
  selectedYear: moment().format("YYYY-MM-DD"),
};

export default {
  namespace: "weekdaysManagement",
  state: {
    ...initData,
  },

  effects: {
    * getWorkingDayList({ payload }, { call, put }) {
      // yield put({ type: "set/WorkingDayList", payload: workingDayMock });
      const { errCode, errMsg, datas = [] } = yield call(getWorkingDayList, payload);
      yield put({ type: "set/WorkingDayList", payload: datas });
      return { errCode, errMsg, datas };
    },
    * getOffDayList({ queryMoment = moment() }, { call, put }) {
      yield put({ type: "set/selectedYear", selectedYear: queryMoment.format("YYYY-MM-DD") });
      const { errCode, errMsg, datas = [] } = yield call(getOffDayList, { year: queryMoment.year() });
      const specialDay = {};
      datas.forEach((item) => {
        const { start } = item;
        const startMoment = moment(start);
        if (startMoment.isValid()) {
          specialDay[startMoment.format("YYYY-MM-DD")] = item;
        }
      });

      yield put({ type: "set/SpecialDay", specialDay });
      return { errCode, errMsg, datas };
    },

    * addWorkingAndOffDay(_, { call, select }) {
      const { workingDayList, realSpecialDay } = yield select(({ weekdaysManagement }) => weekdaysManagement);

      /* TODO: StepThree有一段一样的代码，可以提取出来 */
      const specialDayList = Object.keys(realSpecialDay)
        .sort()
        .map((date) => realSpecialDay[date])
        .filter(({ removed }) => !removed);

      const { errCode, errMsg } = yield call(addWorkingAndOffDay, {
        workingDays: workingDayList.map((item) => item.code), offDays: specialDayList,
      });
      return { errCode, errMsg };
    },
  },
  reducers: {
    "set/WorkingDayList": (state, { payload }) => ({
      ...state,
      workingDayList: payload,
    }),
    "set/SpecialDay": (state, { specialDay }) => ({
      ...state,
      specialDay,
      realSpecialDay: { ...specialDay, ...state.specialDayTemp },
    }),
    "set/SpecialDayTemp": (state, { specialDayTemp }) => {
      return {
        ...state,
        specialDayTemp,
        realSpecialDay: { ...state.specialDay, ...specialDayTemp },
      };
    },
    "set/selectedYear": (state, { selectedYear }) => ({
      ...state,
      selectedYear,
    }),
  },
};
